//
//  HTOrderLineDetialViewController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/27.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTOrderLineDetialViewController.h"
#import "HTGoodSourceCell.h"
#import "HTGoodSourceTypeTwoCell.h"
#import "HTGoodsDetialViewController.h"

#import "HTTruckTypeView.h"
#import "HTRefreshMoreModel.h"


@interface HTOrderLineDetialViewController ()<UITableViewDataSource,UITableViewDelegate,HTTruckTypeViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *headView;


@property (weak, nonatomic) IBOutlet UIView *tapAreaView;
@property (weak, nonatomic) IBOutlet UILabel *truckTypeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *truckTypeImageView;


@property (nonatomic,strong) NSMutableArray *dataSource;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;


@property (nonatomic,strong) HTTruckTypeView *truckLengthTypeView;
//弹框数据
@property (nonatomic,strong) NSMutableArray *selectedLengthData;
@property (nonatomic,strong) HTTruckTypeModel *selectedTruckType;
@property (nonatomic,strong) HTTruckTypeModel *selectedGoodsType;
@property (nonatomic,assign) BOOL isLessThanTruck;

@property (nonatomic,assign) NSInteger pageNumber;
@property (nonatomic,strong) HTRefreshMoreModel *refreshMoreModel;


@end

@implementation HTOrderLineDetialViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupView];
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
    [self configTableView];
    self.pageNumber = 1;
}
- (void)setupView{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.tapAreaView addGestureRecognizer:tap];
    
}

- (void)configTableView{
    self.title = @"线路详情";
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.width = kHTScreenWidth;
    self.tableView.backgroundColor = kBackgroundColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTGoodSourceCell" bundle:nil] forCellReuseIdentifier:goodSourceCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTGoodSourceTypeTwoCell" bundle:nil] forCellReuseIdentifier:goodSourceCellTwo];
    [self configTableHeader];
    [self configTableFooter];
    self.tableView.mj_header = self.header;
    self.tableView.mj_footer = self.footer;
    self.noDataView = [[HTNoDataView alloc]initWithFrame:self.tableView.bounds];
    self.noDataView.showMessage = @"暂无货源";
    self.tableView.estimatedRowHeight =0;
    self.tableView.estimatedSectionHeaderHeight =0;
    self.tableView.estimatedSectionFooterHeight =0;
    
    
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark --- tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     [tableView tableViewDisplayView:self.noDataView ifNecessaryForRowCount:self.dataSource.count];
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 185;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTGoodSearchModel *model = self.dataSource[indexPath.row];
    if (model.pricers== nil ||model.pricers.length <= 0) {
        HTGoodSourceTypeTwoCell *cell = (HTGoodSourceTypeTwoCell *)[tableView dequeueReusableCellWithIdentifier:goodSourceCellTwo forIndexPath:indexPath withController:self];
        cell.searchModel = model;
        return cell;
    }else{
        HTGoodSourceCell *cell = (HTGoodSourceCell*) [tableView dequeueReusableCellWithIdentifier:goodSourceCell forIndexPath:indexPath withController:self];
        cell.searchModel = model;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HTGoodSearchModel *model = self.dataSource[indexPath.row];
    HTGoodsDetialViewController *detial = [[HTGoodsDetialViewController alloc]init];
    detial.searchModel = model;
    [self.navigationController pushViewController:detial animated:YES];
}


#pragma mark --- 车长车型弹框
- (void)didTapGesture:(UITapGestureRecognizer *)sender{
    if (!self.truckLengthTypeView) {
        [self setupTruckLengthTypeView];
        [self setTabSelected:YES];
    }else{
        [self removeTruckLengthTypeView];
        [self setTabSelected:NO];
    }
}

- (void)setupTruckLengthTypeView{
    if (!self.truckLengthTypeView) {
        self.truckLengthTypeView = [[HTTruckTypeView alloc]initWithFrame:CGRectMake(0, self.headView.bottom, kHTScreenWidth, kHTScreenHeight - self.headView.bottom - kHTNavicationBarAndStatusBar)];
        self.truckLengthTypeView.delegate = self;
        self.truckLengthTypeView.selectedGoodType = self.selectedGoodsType;
        self.truckLengthTypeView.selectedTruckType  = self.selectedTruckType;
        self.truckLengthTypeView.selectedLengths = self.selectedLengthData;
        self.truckLengthTypeView.isLessThanTruck= self.isLessThanTruck;
        [self.truckLengthTypeView reloadContentData];
        __weak __typeof(self)weakSelf = self;
        self.truckLengthTypeView.blockCallBack = ^{
            [weakSelf removeTruckLengthTypeView];
            [weakSelf setTabSelected:NO];
        };
        [self.view addSubview:self.truckLengthTypeView];
    }
}
//移除弹框，车长车型
- (void)removeTruckLengthTypeView{
    if (self.truckLengthTypeView) {
        [self.truckLengthTypeView removeFromSuperview];
        self.truckLengthTypeView = nil;
    }
}
- (void)didClickConformWithLengths:(NSMutableArray *)lengthsData TruckType:(HTTruckTypeModel *)truckType GoodType:(HTTruckTypeModel *)goodsType isLessThanTruck:(BOOL)isLessThanTruck{
    self.selectedLengthData = lengthsData;
    self.selectedTruckType = truckType;
    self.selectedGoodsType = goodsType;
    self.isLessThanTruck = isLessThanTruck;
    NSString *total = @"";
    total = [NSString stringWithFormat:@"%@,%@",total,[HTUtils sortLengthDataDisplayStringWithArray:lengthsData]];
    NSInteger index = 1;
    if ([total isEqualToString:@",不限车长"]) {
        total = @"";
        index = 0;
    }
    if (!(truckType.truckTypeModelType == TruckTypeModelTypeUnlimited)) {
        if (index < 2) {
            total = [NSString stringWithFormat:@"%@,%@",total,truckType.title];
            index++;
        }
    }
    if (!(goodsType.truckTypeModelType == TruckTypeModelTypeUnlimited)) {
        if (index < 2) {
            total = [NSString stringWithFormat:@"%@,%@",total,goodsType.title];
            index ++;
        }
    }
    if (total.length <= 0) {
        total = @"车长车型";
    }else{
        total = [total substringFromIndex:1];
    }
    self.truckTypeLabel.text = total;
    [self removeTruckLengthTypeView];
    [self setTabSelected:NO];
}
- (void)setTabSelected:(BOOL)selected{
    if (selected) {
         [self setTabViewSelected:YES withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
    }else{
         [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
    }
}
- (void)setTabViewSelected:(BOOL)selected withImageView:(UIImageView *)imageView withLabel:(UILabel *)label{
    if (selected) {
        imageView.image = [[UIImage imageNamed:@"arrow_solid_up"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = kBlueColor;
        label.textColor = kBlueColor;
    }else{
        imageView.image = [[UIImage imageNamed:@"arrow_solid_down"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = [UIColor blackColor];
        label.textColor = [UIColor blackColor];
    }
}

#pragma mark --- 网络请求
//货源搜索数据
- (void)netLoadGoodsSearchWithIndex:(NSInteger)index{
    NSString *length = [HTUtils sortLengthDataDisplayStringWithArray:self.selectedLengthData];
    NSString *goosType = @"";
    if (self.selectedGoodsType != nil && ![self.selectedGoodsType.title isEqualToString:@"不限"]) {
        goosType = self.selectedGoodsType.title;
    }
    NSString *carType = @"";
    if (self.selectedTruckType != nil &&![self.selectedTruckType.title isEqualToString:@"不限"]) {
        carType = self.selectedTruckType.title;
    }
    [HTHttpRequestManager requestGoodsSearchWithStarname:self.lineModel.fromaddr endname:self.lineModel.toaddr length:length goodstype:@"" cartype:carType cargotype:[NSString stringWithFormat:@"%d",self.isLessThanTruck]  page:[NSString stringWithFormat:@"%ld",index]  success:^(id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        DBLog(@"货源：%@",responseObject);
        if (!responseObject) {
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            return;
        }
        if (self.pageNumber == 1) {
            //代表是刷新的
            [self.dataSource removeAllObjects];
        }
        NSArray *result = responseObject[@"data"][@"data"];
        NSMutableArray *dataResult = [HTGoodSearchModel mj_objectArrayWithKeyValuesArray:result];
        [self.dataSource addObjectsFromArray:dataResult];
        NSDictionary *dic = responseObject[@"data"][@"meta"];
        self.refreshMoreModel = [HTRefreshMoreModel mj_objectWithKeyValues:dic[@"pagination"]];
        NSString *currentPage = self.refreshMoreModel.current_page;
        self.pageNumber = [currentPage integerValue];
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    }];
    
}
- (void)loadMoreData{
    [self.tableView.mj_header endRefreshing];
    if (self.dataSource.count == 0) {
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        return;
    }
    self.pageNumber ++;
    if (self.refreshMoreModel && [self.refreshMoreModel.total integerValue] < self.pageNumber) {
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        return;
    }
    [self netLoadGoodsSearchWithIndex:self.pageNumber];
    
}
- (void)loadNewData{
    self.pageNumber = 1;
    [self.tableView.mj_footer endRefreshing];
    [self netLoadGoodsSearchWithIndex:1];
}




@end
